﻿using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.SceneManagement;
using XLua;

public class AssetUtil : IUtil
{
    private readonly Dictionary<string, Object> _cacheDic = new Dictionary<string, Object>();
    // 刷新场景加载进度
    private UnityAction refreshSceneLoadingProgress;
    public void Init()
    {
        Debug.Log("asset inited!");
    }

    public void Tick()
    {
        refreshSceneLoadingProgress?.Invoke();
    }

    public void Uninit()
    {
        Debug.Log("asset uninited!");
    }
   
    /// <summary>
    /// 场景加载通用接口
    /// </summary>
    /// <param name="sceneName"></param>
    /// <param name="loadingProgress"></param>
    /// <param name="loadFinished"></param>
    [LuaCallCSharp]
    public void LoadSceneAsync(string sceneName, UnityAction<float> loadingProgress, UnityAction loadFinished)
    {
        // 如果当前场景已经是目标场景
        if (sceneName == SceneManager.GetActiveScene().name)
        {
            loadingProgress?.Invoke(1);
            loadFinished?.Invoke();
            return;
        }
        AsyncOperation ao = SceneManager.LoadSceneAsync(sceneName);
        refreshSceneLoadingProgress = () =>
        {
            loadingProgress?.Invoke(ao.progress);
            if (ao.progress == 1.0f)
            {
                loadFinished?.Invoke();
                refreshSceneLoadingProgress = null;
                ao = null;
            }
        };
    }

    /// <summary>
    /// 通用加载对应资源接口
    /// </summary>
    /// <param name="path"></param>
    /// <returns></returns>
    [LuaCallCSharp]
    public GameObject LoadPrefab(string path)
    {
        return LoadAsset<GameObject>(path);
    }
    [LuaCallCSharp]
    public Sprite LoadSprite(string path)
    {
        return LoadAsset<Sprite>(path);
    }
    [LuaCallCSharp]
    public AudioClip LoadAudio(string path)
    {
        return LoadAsset<AudioClip>(path);
    }

    // 通用资源加载
    private T LoadAsset<T>(string path)
        where T : Object
    {
        if (!_cacheDic.TryGetValue(path, out Object asset))
        {
            asset = Resources.Load(path);
            // 如果是GameObject直接实例化出来
            if (asset != null && asset is GameObject)
                asset = Object.Instantiate(asset);
            // 判断是否加载成功
            if (asset != null)
                _cacheDic.Add(path, asset);
            else
                Debug.LogError($"load asset failed.type:{typeof(T)}|path:{path}");
        }
        return asset as T;
    }
}